//
//  WPHTTPSessionManager.m
//  wobingwoyi
//
//  Created by WGP on 16/7/22.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPNetWorkManager.h"
#import "JPUSHService.h"

@interface WPNetWorkManager ()<UIAlertViewDelegate>

@end

static NSString *const WPBaseURLString = @"https://www.wobingwoyi.com:8443/wbwy/";
//static NSString *const WPBaseURLString = @"http://192.168.0.107:8080/wbwy/";

@implementation WPNetWorkManager

+(instancetype)sharedNetWorkManager
{
    static WPNetWorkManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        instance = [[self alloc] initWithBaseURL:[NSURL URLWithString:WPBaseURLString]];
       
    instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/plain",@"text/html", nil];
        
        instance.requestSerializer.timeoutInterval = 10;
       
//        每次程序重新启动都要重新设置一次请求头
        if ([WPUserAccountViewModel sharedInstance].userAccount.token)
        {
             NSString *tokenStr = [[WPUserAccountViewModel sharedInstance].userAccount.token yy_modelToJSONString];
            [instance.requestSerializer setValue:tokenStr forHTTPHeaderField:@"token"];
        }
    });
    return instance;
}


#pragma mark - 多张图片上传
-(void)uploadImagesWithURL:(NSString *)URLStr imagesArr:(NSArray *)images parameterOfimages:(NSString *)parameter parametersDict:(NSDictionary *)parameters compressionRatio:(float)ratio uploadProgressBlock:(uploadProgress)uploadProgressBlock succeedBlock:(requestSuccess)succeedBlock failedBlock:(requestFailure)failedBlock
{
    if (images.count == 0) {
        WPLog(@"上传内容没有包含图片");
        return;
    }
    for (int i = 0; i < images.count; i++) {
        if (![images[i] isKindOfClass:[UIImage class]]) {
            return;
        }
    }
    
    [self POST:URLStr parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        // 设置上传图片的名字
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *dateString = [formatter stringFromDate:[NSDate date]];
        
        for (int i = 0; i < images.count; i++) {
            NSString *fileName = [NSString stringWithFormat:@"%@%zd.jpg",dateString,i];
            
            NSData *imageData;
            if (ratio > 0.0f && ratio < 1.0f) {
                imageData = UIImageJPEGRepresentation(images[i], ratio);
            }else{
                imageData = UIImageJPEGRepresentation(images[i], 1.0f);
            }
            [formData appendPartWithFileData:imageData name:parameter fileName:fileName mimeType:@"image/jpeg"];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        uploadProgressBlock(uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        succeedBlock(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failedBlock(error);
        
    }];
}

#pragma mark - 网络状态监测
-(void)startMonitoring
{
    //1.创建网络监测者
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    
    /*枚举里面四个状态  分别对应 未知 无网络 数据 WiFi
     typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
     AFNetworkReachabilityStatusUnknown          = -1,      未知
     AFNetworkReachabilityStatusNotReachable     = 0,       无网络
     AFNetworkReachabilityStatusReachableViaWWAN = 1,       蜂窝数据网络
     AFNetworkReachabilityStatusReachableViaWiFi = 2,       WiFi
     };
     */
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        //这里是监测到网络改变的block  可以写成switch方便
        //在里面可以随便写事件
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                WPLog(@"未知网络状态");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                WPLog(@"无网络");
                [self networkReachabilityStatusNotReachable];
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN:
                WPLog(@"蜂窝数据网");
                [self networkReachabilityStatusReachableViaWWAN];
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi:
                WPLog(@"WiFi网络");
                
                break;
                
            default:
                break;
        }
        
    }] ;
    
    [manager startMonitoring];
}

-(void)networkReachabilityStatusNotReachable
{
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"友情提示" message:@"您处于无网络状态" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去设置", nil];
//    [alert show];
}

-(void)networkReachabilityStatusReachableViaWWAN
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"友情提示" message:@"您没有开启Wi-Fi,是否继续使用移动网络播放" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"继续播放", nil];
    [alert show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        WPLog(@"继续使用移动数据");
        if ([self.delegate respondsToSelector:@selector(continueToUseWWWA)]) {
            
            [self.delegate continueToUseWWWA];
        }
    }
}

- (void)userLogin
{
    WPUserAccount *userAccount = [WPUserAccountViewModel sharedInstance].userAccount;
    
    if (!userAccount.user)
    {
        return ;
    }
    
    NSString *url = @"user/login.do";
    NSDictionary *dict = @{@"account":userAccount.user.account,@"password":userAccount.user.password};
    
    [self POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject){
        
        NSDictionary *responseDic = (NSDictionary *)responseObject;
        
        if ([responseDic[@"result"] isEqualToString:@"success"])
        {
            //            保存用户信息
            WPUserAccount *userAccount = [WPUserAccount yy_modelWithDictionary:responseDic[@"detail"]];
            [userAccount saveUserAccount];
            
            //            设置请求头
            NSString *tokenStr = [userAccount.token yy_modelToJSONString];
            [[WPNetWorkManager sharedNetWorkManager].requestSerializer setValue:tokenStr forHTTPHeaderField:@"token"];
            
            //用于绑定Alias的  使用NSString 即可
            [JPUSHService setAlias:[NSString stringWithFormat:@"%zd",userAccount.user.id] callbackSelector:nil object:self];
        }
        else
        {
            NSFileManager *defaultManager = [NSFileManager defaultManager];
            if([defaultManager removeItemAtPath:filepath error:NULL])
            {
//                WPLog(@"删除归档文件成功");
            }
            [defaultManager removeItemAtPath:MRFilePath error:NULL];
            
            [WPUserAccountViewModel sharedInstance].userAccount = nil;
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];

}

@end










